package com.guaoran.study.retry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Desc： todo xxx
 * @Auth guaoran
 * @Date 2020/9/7 下午5:04.
 */
@Service
public class RetryService {
    private static final Logger LOGGER = LoggerFactory.getLogger(RetryService.class);

    private AtomicInteger count = new AtomicInteger(1);


    // 重试  10次 ，最多重试 1000次，当超过最大重试次数后，mock recover 方法
    @Retryable(value = { RemoteAccessException.class }, maxAttemptsExpression = "${retry.maxAttempts:10}",
            backoff = @Backoff(delayExpression = "${retry.backoff:100}"))
    public String retry() {
        LOGGER.info("start to retry : " + count.getAndIncrement());

        throw new RemoteAccessException("here " + count.get());
    }

    @Recover
    public String recover(RemoteAccessException t) {
        LOGGER.info("SampleRetryService.recover:{}", t.getClass().getName());
        return "recover";
    }
}
